package com.customization.unionpay.contract.serivce.impl;

import com.customization.unionpay.contract.dao.BaseContractSynDataDao;
import com.customization.unionpay.contract.serivce.IContractBaseService;
import com.engine.core.impl.Service;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mr_d
 * @Date 2024/7/17
 **/
public class ContractBaseServiceImpl extends Service implements IContractBaseService {

    public static Logger log = LoggerFactory.getLogger("ContractBaseServiceImpl", ContractBaseServiceImpl.class.getName());


    @Override
    public String marketingApply(List<String> contractNo, String amount, String supplierName, Integer userId) {
        return "Success";
    }

    /**
     * 营销共享合同集主表数据存储
     * @param userId SQ申请人(SQ申请组织、SQ申请部门)
     * @param filingDate SQ归档日期
     * @param activityName SQ单活动名称
     * @param shareNo SQ单：共享合同编号
     * @param contractNo 关联合同号
     * @param sQAmount SQ金额（内部出资金额）
     * @param signatories SQ单供应商名称
     * @return
     */
    @Override
    public String marketingAdd(Integer userId, String filingDate, String activityName, String shareNo, String sQAmount, List<String> contractNo,List<String> signatories) {
        User user = new User(userId);
        String supplier = userId.toString();
        String supplierDept = user.getUserDepartment() +"";
        String supplierCompany = user.getUserSubCompany1() + "";

        // 1. 支出合同台账存储
        // 1.1 主表
        Map<String,String> main = new HashMap<>();
        // 合同名称    SQ单活动名称+营销共享合同
        main.put("htmc",activityName + "+营销共享合同");
        // 合同编号    SQ单：共享合同编号
        main.put("htbh",shareNo);
        // 合同经办机构 默认等于SQ申请公司
        main.put("htjbjg",supplierCompany);
        // 合同经办部门 默认等于SQ申请部门
        main.put("htjbbm",supplierDept);
        // 合同经办人 默认等于SQ申请人
        main.put("htjbr",supplier);
        // 合同归档日  默认等于SQ归档日期
        main.put("htgdr",filingDate);
        // 合同签订时间  默认等于SQ归档日期
        main.put("htqdsj",filingDate);
        // 合同到期日 默认等于SQ归档日期
        main.put("htdqr",filingDate);
        // 合同付款预设标的额 默认等于SQ金额
        main.put("htfkysbde",sQAmount);
        // 合同收付款关系  支出合同
        main.put("htsfkgx","1");
        // 合同业务类型 默认等于其他
        main.put("htywlx","6");
        // 合同属性 默认虚拟合同
        main.put("htzx","2");
        // 合同状态 默认有效
        main.put("htzt","1");
        // 合同种类 默认费用类
        main.put("htzl","0");
        // 合同备案时间 默认等于流程审批通过时间
//        main.put("htbasj","");
        // 合同关联信息  共享额度营销合同
        main.put("htglxx","2");
        // 收支匹配合同信息 默认空
        main.put("szpphtxx","");
        // 银行大协议关联信息 默认空
        main.put("yhdxyglxx","");
        // 共享额度营销合同关联信息
//        main.put("gxedyxhtglxx",linkNo);
//        // 合同原币总金额 默认等于合同付款标的额
//        main.put("htybzje",amount);
//        // 合同签订币种 默认等于人民币
//        main.put("htqdbz","");//TODO：
//        // 合同汇率  根据币种主数据带出
//        main.put("hthl","");//TODO：
        // 合同RMB总金额 支出合同默认等于[合同付款预设标的额]
        main.put("htrmbzje",sQAmount);
//        // 合同不含税金额
//        main.put("htbhsje",amount);
//        // 费用化金额
//        main.put("fyhje",costAmount);
//        // 资本化金额
//        main.put("zbhje",capitalizedAmount);

        BaseContractSynDataDao dataDao = new BaseContractSynDataDao();
        dataDao.addYXGXContractData(main);

        String id = dataDao.selectZchttzIdByHtbh(shareNo);
        // 1.2 签约方明细表
        if( null != signatories && signatories.size() > 0){
            addYXGXContractSignatories(id,signatories);
        }
        // 1.3 关联共享营销合同明细表
        if( null != contractNo && contractNo.size() > 0){
            addYXGXContractDetail(id,contractNo);
        }
        marketingPlanAdd(shareNo,sQAmount,supplierDept);
        return id;
    }

    private boolean addYXGXContractDetail(String mainId, List<String> mxList) {
        BaseContractSynDataDao dataDao = new BaseContractSynDataDao();

        for(int i = 0; i < mxList.size();i++){
            String htbh = mxList.get(i);
            Map<String,String> map = dataDao.selectFKContractVirtualMain(htbh);
            map.put("mainid",mainId);
            dataDao.addYXGXContractDetailData(map);
        }
        return true;
    }

    /**
     * 营销共享合同集付款计划台账
     * @param htbh 合同编号
     * @param amount 计划付款金额
     * @param dept 计划责任部门
     * @return
     */
    @Override
    public boolean marketingPlanAdd(String htbh,String amount,String dept) {
        BaseContractSynDataDao dataDao = new BaseContractSynDataDao();
        Map<String,String> map = dataDao.selectFKContractPlanMain(htbh);
        map.put("jhfkje",amount);//计划付款不含税金额
        map.put("jhzrbm",dept);//计划责任部门
        dataDao.addYXGXContractPlanData(map);

        return true;
    }

    private boolean addYXGXContractSignatories(String mainId, List<String> signatories) {
        BaseContractSynDataDao dataDao = new BaseContractSynDataDao();

        for(int i = 0; i < signatories.size();i++){
            String name = signatories.get(i);
            Map<String,String> map = new HashMap<>();
            map.put("mainid",mainId);
            // 是否银联方
//            map.put("","");
            // 签约方名称
            map.put("qyfmc",name);
            // 签约方统一社会信用代码
//            map.put("qyftyshxydm","");
            // 签约方开户银行
//            map.put("qyfkhyh","");
            // 签约方开户支行
//            map.put("qyfkhzh","");
            // 签约方开户账号
//            map.put("qyfkhzh","");
            dataDao.addYXGXContractSigatoriesData(map);
        }
        return true;
    }

    @Override
    public void updateAmountFunded(Integer operateType ,Integer contractPlanId,String amount) {
        log.info("updateAmountFunded operateType = "+operateType + "contractPlanId = " + contractPlanId +" amount = " +amount );
        RecordSetTrans rst = new RecordSetTrans();
        String sql = "";
        //1 提交 2 回退 uf_htjhfktz spzje
        // 3 归档 uf_zchttz yfkhsqsqje
        try {
            if(1 == operateType){
                sql = "update uf_htjhfktz set spzje = nvl(spzje,0)+? where id = ?";
                rst.executeUpdate(sql,amount,contractPlanId);
            }else if(2 == operateType){
                sql = "update uf_htjhfktz set spzje = nvl(spzje,0)-? where id = ?";
                rst.executeUpdate(sql,amount,contractPlanId);
            }else if(3==operateType){
                sql = "update uf_htjhfktz set spzje = nvl(spzje,0)-?,yfkje = nvl(yfkje,0)+?,nbczljje = nvl(nbczljje,0)+? where id = ?";
                rst.executeUpdate(sql,amount,amount,amount,contractPlanId);
                //更新合同主表
                sql = "select htbh from uf_htjhfktz where id = ?";
                rst.executeQuery(sql,contractPlanId);
                if(rst.next()){
                    int htId = rst.getInt("htbh");
                    sql = "update uf_zchttz set yfkhsqsqje = nvl(yfkhsqsqje,0)+? where id = ?";
                    rst.executeUpdate(sql,amount,htId);
                }
            }else{
                return;
            }
            rst.commit();
        } catch (Exception e) {
            rst.rollback();
            log.error("updateAmountFunded error",e);
        }
    }

    @Override
    public void updateHX(Integer contractPlanId , String amount) {
        log.info("updateHX contractPlanId = "+contractPlanId  +" amount = " +amount );

        RecordSetTrans rst = new RecordSetTrans();
        try {
            //更新明细表
            String sql = "update uf_htjhfktz set lzje = nvl(lzje,0) + ? where id = ?";
            rst.executeUpdate(sql,amount,contractPlanId);

            //更新主表
            //更新合同主表
            sql = "select htbh from uf_htjhfktz where id = ?";
            rst.executeQuery(sql,contractPlanId);
            if(rst.next()){
                int htId = rst.getInt("htbh");
                sql = "update uf_zchttz set lzje = nvl(lzje,0)+? where id = ?";
                rst.executeUpdate(sql,amount,htId);
            }
            rst.commit();
        } catch (Exception e) {
            rst.rollback();
            log.error("updateHX error",e);
        }
    }

    @Override
    public void updateJTZY(Integer operateType, Integer contractPlanId, String amount) {
        log.info("updateJTZY operateType = "+operateType + "contractPlanId = " + contractPlanId +" amount = " +amount );
        RecordSetTrans rst = new RecordSetTrans();
        String sql = "";
        //1 提交 2 回退 uf_htjhfktz spzje
        // 3 归档 uf_zchttz yfkhsqsqje
        try {
            if(1 == operateType){
                sql = "update uf_htjhfktz set spzje = nvl(spzje,0)+?,yzyhtjtjeyf=nvl(yzyhtjtjeyf,0)+? where id = ?";
                rst.executeUpdate(sql,amount,amount,contractPlanId);
            }else if(2 == operateType){
                sql = "update uf_htjhfktz set spzje = nvl(spzje,0)+?,yzyhtjtjeyf=nvl(yzyhtjtjeyf,0)-? where id = ?";
                rst.executeUpdate(sql,amount,amount,contractPlanId);
            }else if(3==operateType){
                sql = "update uf_htjhfktz set spzje = nvl(spzje,0)-?,yfkje = nvl(yfkje,0)+? where id = ?";
                rst.executeUpdate(sql,amount,amount,contractPlanId);
                //更新合同主表
                sql = "select htbh from uf_htjhfktz where id = ?";
                rst.executeQuery(sql,contractPlanId);
                if(rst.next()){
                    int htId = rst.getInt("htbh");
                    sql = "update uf_zchttz set yfkhsqsqje = nvl(yfkhsqsqje,0)+? where id = ?";
                    rst.executeUpdate(sql,amount,htId);
                }
            }else{
                return;
            }
            rst.commit();
        } catch (Exception e) {
            rst.rollback();
            log.error("updateJTZY error",e);
        }
    }

    @Override
    public void updateLZJE(Integer operateType, Integer contractPlanId, String amount) {
        log.info("updateJTZY operateType = "+operateType + "contractPlanId = " + contractPlanId +" amount = " +amount );
        RecordSetTrans rst = new RecordSetTrans();
        String sql = "";
        //1 提交 2 回退 uf_htjhfktz spzje
        // 3 归档 uf_zchttz yfkhsqsqje
        try {
            if(1 == operateType){
                sql = "update uf_htjhfktz set jtye = nvl(jtye,0)-? where id = ?";
                rst.executeUpdate(sql,amount,contractPlanId);
            }else if(2 == operateType){
                sql = "update uf_htjhfktz set jtye = nvl(jtye,0)+? where id = ?";
                rst.executeUpdate(sql,amount,contractPlanId);
            }else if(3==operateType){
                sql = "update uf_htjhfktz set lzje = nvl(lzje,0)+? where id = ?";
                rst.executeUpdate(sql,amount,contractPlanId);
                //更新合同主表
                sql = "select htbh from uf_htjhfktz where id = ?";
                rst.executeQuery(sql,contractPlanId);
                if(rst.next()){
                    int htId = rst.getInt("htbh");
                    sql = "update uf_zchttz set lzje = nvl(lzje,0)+? where id = ?";
                    rst.executeUpdate(sql,amount,htId);
                }
            }else{
                return;
            }
            rst.commit();
        } catch (Exception e) {
            rst.rollback();
            log.error("updateJTZY error",e);
        }
    }

    @Override
    public void syncGXStatus(List<String> contractList, Integer operateType) {
        log.info("syncGXStatus contractList = "+contractList.toString() + "operateType = " + operateType);
        RecordSet rs = new RecordSet();
        String sql = "update uf_zchttz set gxhtzt = ? where id in (" + String.join(",",contractList) +")";
        rs.executeUpdate(sql);
    }

    @Override
    public Map<String,Object> getSKContractPlanDetailById(Integer planId,String params) {
        Map<String,Object> res = new HashMap<>();
        String sql = "select " + params + " from uf_htskjhtz where id = ? ";
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(sql,planId);
        while(recordSet.next()){
            for (String columns : params.split(",")) {
                res.put(columns, Util.null2String(recordSet.getString(columns)));
            }
        }
        return res;
    }

    @Override
    public Map<String,Object> getSKContractDetailById(Integer id,String params) {
        Map<String,Object> res = new HashMap<>();
        String sql = "select " + params + " from uf_skhttz where id = ? ";
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(sql,id);
        while(recordSet.next()){
            for (String columns : params.split(",")) {
                res.put(columns, Util.null2String(recordSet.getString(columns)));
            }
        }
        return res;
    }

    @Override
    public boolean updateContractPlanById(Integer planId, Integer tableType, Integer type, String amount) {
        if(0 != tableType && 1 != tableType && 0 != type && 1 != type && 2 != type){
            return false;
        }
        // tableType = 0 更新收款计划台帐 uf_htskjhtz
        // tableType = 1 更新合同主表 uf_skhttz
        // type = 0 ; srbzje  收入报账金额
        //  type = 1 , ysbzje  预收报账金额
        //  type = 2 , ysjzje  预收结转金额
        RecordSetTrans rst = new RecordSetTrans();
        try {
            String tableName;
            String fieldName;
            if (tableType == 0){
                //更新合同计划明细
                tableName = "uf_htskjhtz";
            }else{
                //更新合同主表
                tableName = "uf_skhttz";
            }
            if (type == 0){
                fieldName = "srbzje";
            }else if (type == 1){
                fieldName = "ysbzje";
            }else{
                fieldName = "ysjzje";
            }
            String sql = "update " + tableName + " set " + fieldName + " = nvl(" + fieldName + ",0) + ? where id = ?";
//            String sql = (0 == type) ? "update " + tableName + " set srbzje = nvl(srbzje,0) + ? where id = ?"
//                    : "update " + tableName + " set ysbzje = nvl(ysbzje,0) + ? where id = ?";
            rst.executeUpdate(sql,amount,planId);
            rst.commit();
        } catch (Exception e) {
            log.error("updateContractPlanById error",e);
            rst.rollback();
            return false;
        }
        return true;
    }

    @Override
    public boolean updateContractPlanDateById(Integer planId, String lYStartDate, String lYEndDate, String planDate) {
        RecordSet rs = new RecordSet();
        try {
            if(StringUtils.isNotBlank(lYStartDate)){
                rs.executeUpdate("update uf_htskjhtz set lykssj = ? where id = ?" ,lYStartDate,planId);
            }
            if(StringUtils.isNotBlank(lYEndDate)){
                rs.executeUpdate("update uf_htskjhtz set lyjssj = ? where id = ?" ,lYEndDate,planId);
            }
            if(StringUtils.isNotBlank(planDate)){
                rs.executeUpdate("update uf_htskjhtz set jhskrq = ? where id = ?" ,planDate,planId);
            }
        } catch (Exception e) {
            log.error("updateContractPlanById error" ,e);
            return true;
        }
        return true;
    }

    @Override
    public Map<String, Object> checkSigner(Map params) {
        Map<String,Object> res = new HashMap<>();
        return res;
    }

    @Override
    public void createSKDetail(Integer planId, String lyStartTime, String lyEndTime, String skPlanDate, String planAmount, String skAmount) {
        // （1）收款计划编号：
        // （2）履约开始时间：
        // （3）履约结束时间：
        // （4）计划收款日期：
        // （5）计划收款金额：
        // （6）收款金额：
        // 除以上内容外的字段沿用第一行收款计划行的信息

    }

    @Override
    public void updateHx(Integer lymxh, String bchxje) {
    }

    @Override
    public void syncGxStatus(List<String> list, int i) {

    }
}
